import HandleBtn from '@/components/HandleBar/btn';
import { ProTable, type ProColumns } from '@/components/Pro';
import {
  historyDataControllerBmuHistoryData,
  historyDataControllerHistoryDataExport as exportDataReport,
} from '@/services/ess/historicalData';
import { downloadFetch } from '@/utils/downloadFile';
import { Link, useIntl } from '@umijs/max';
import { message } from 'antd';
import dayjs, { Dayjs } from 'dayjs';
import React, { useEffect, useState } from 'react';

interface Props {
  tabIndex?: string;
  deviceCode?: string;
  deviceType?: string;
  areaId?: string;
  selectedKeys?: string[];
}

const BatteryModuleInfo: React.FC<Props> = ({ deviceCode, deviceType, areaId, selectedKeys }) => {
  const intl = useIntl(); // 获取国际化实例
  const [data, setData] = useState<API.BmuPageDataDTO[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [params, setParams] = useState({
    current: 1,
    pageSize: 20,
    startDate: dayjs().startOf('day').format('YYYY-MM-DDTHH:mm:ss'),
    endDate: dayjs().format('YYYY-MM-DDTHH:mm:ss'),
  });
  const [dynamicColumns, setDynamicColumns] = useState<ProColumns<any>[]>([]);
  const [selectedColumns, setSelectedColumns] = useState<string[]>([]);

  const isEnglish = intl.locale === 'en-US';

  const baseColumns: ProColumns<any>[] = [
    {
      title: intl.formatMessage({ id: 'data.s/N' }), // 序号
      key: 'index',
      valueType: 'index',
      width: 60,
      dataIndex: 'pageIndex',
    },
    {
      title: intl.formatMessage({ id: 'data.acquisitionTime' }), // 采集时间
      dataIndex: 'collectTime',
      key: 'collectTime',
      valueType: 'dateTimeRange',
      width: 200,
      initialValue: [dayjs().startOf('day'), dayjs()],
      render: (_, record) => {
        return <span>{record.collectTime}</span>;
      },
      search: {
        transform: (value) => {
          return {
            startDate: value ? dayjs(value[0]).format('YYYY-MM-DDTHH:mm:ss') : undefined,
            endDate: value ? dayjs(value[1]).format('YYYY-MM-DDTHH:mm:ss') : undefined,
          };
        },
      },
      fieldProps: {
        onCalendarChange: (dates: [Dayjs, Dayjs]) => {
          if (dates && dates.length === 2) {
            const [start, end] = dates;
            if (dayjs(end).diff(start, 'day') > 31) {
              message.warning(intl.formatMessage({ id: 'data.sDays' }));
            }
          }
        },
        disabledDate: (current: Dayjs | null) => {
          return current && current > dayjs().endOf('day');
        },
      },
    },
    {
      title: intl.formatMessage({ id: 'data.reportingTime' }), // 上报时间
      dataIndex: 'reportTime',
      key: 'reportTime',
      hideInSearch: true,
      width: 200,
      render: (_, record) => {
        return <span>{record.reportTime}</span>;
      },
    },
    {
      title: intl.formatMessage({ id: 'data.moduleName' }), // 模组名称
      dataIndex: 'moduleName',
      key: 'moduleName',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.current' }), // 电流(A)
      dataIndex: 'current',
      key: 'current',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.balancedCurrent' }), // 均衡电流(A)
      dataIndex: 'balanceCurrent',
      key: 'balanceCurrent',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.totalVoltageOfModule' }), // 模组总电压(V)
      dataIndex: 'moduleTotalVoltage',
      key: 'moduleTotalVoltage',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.avgVoltageOfCells' }), // 单体平均电压(V)
      dataIndex: 'cellAverageVoltage',
      key: 'cellAverageVoltage',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.avgTemperatureOfCells' }), // 单体平均温度(℃)
      dataIndex: 'cellAverageTemperature',
      key: 'cellAverageTemperature',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.vmax' }), // 最大电压(V)
      dataIndex: 'maxVoltage',
      key: 'maxVoltage',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.vmaxPosition' }), // 最大电压位置
      dataIndex: 'maxVoltagePosition',
      key: 'maxVoltagePosition',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.vmin' }), // 最小电压(V)
      dataIndex: 'minVoltage',
      key: 'minVoltage',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.vminPosition' }), // 最小电压位置
      dataIndex: 'minVoltagePosition',
      hideInSearch: true,
      key: 'minVoltagePosition',
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.tmax' }), // 最大温度(℃)
      dataIndex: 'maxTemperature',
      key: 'maxTemperature',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.tmaxPosition' }), // 最大温度位置
      dataIndex: 'maxTemperaturePosition',
      key: 'maxTemperaturePosition',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.tmin' }), // 最小温度(℃)
      dataIndex: 'minTemperature',
      key: 'minTemperature',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.tminPosition' }), // 最小温度位置
      dataIndex: 'minTemperaturePosition',
      hideInSearch: true,
      key: 'minTemperaturePosition',
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.maxCurrent' }), // 最大电流(A)
      dataIndex: 'imax',
      key: 'imax',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.maxCurrentPosition' }), // 最大电流位置
      dataIndex: 'imaxIdx',
      key: 'imaxIdx',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.minCurrent' }), // 最小电流(A)
      dataIndex: 'imin',
      key: 'imin',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.minCurrentPosition' }), // 最小电流位置
      dataIndex: 'iminIdx',
      key: 'iminIdx',
      hideInSearch: true,
      width: 150,
    },
  ];

  const fetchData = async (params: {
    current: number;
    pageSize: number;
    startDate: string;
    endDate: string;
  }) => {
    setLoading(true);
    const response = await historyDataControllerBmuHistoryData({
      current: params.current,
      pageSize: params.pageSize,
      startDate: params.startDate, // 格式化为 LocalDateTime 格式
      endDate: params.endDate,
      deviceCode,
      deviceType,
      areaId,
    });

    if (response.success && response.data && response.data?.records) {
      const records = response.data.records.map((record, index) => {
        const tempArray = record.tempData ? record.tempData.split(';') : [];
        const volArray = record.voltData ? record.voltData.split(';') : [];
        const tempData: any = {};
        const volData: any = {};

        tempArray.forEach((temp, idx) => {
          tempData[`UnitTemp${idx + 1}`] = temp;
        });

        volArray.forEach((vol, idx) => {
          volData[`UnitVol${idx + 1}`] = vol;
        });

        return {
          pageIndex: (params.current - 1) * params.pageSize + index + 1,
          collectTime: record.collectTime,
          reportTime: record.reportTime,
          moduleName: record.bmuName,
          current: record.current,
          balanceCurrent: record.bcurrent,
          voltage: record.voltage,
          moduleTotalVoltage: record.voltage,
          cellAverageVoltage: record.cellAvgVol,
          cellAverageTemperature: record.cellAvgTemp,
          maxVoltage: record.vmax,
          maxVoltagePosition: record.vmaxIdx,
          minVoltage: record.vmin,
          minVoltagePosition: record.vminIdx,
          maxTemperature: record.tmax,
          maxTemperaturePosition: record.tmaxIdx,
          minTemperature: record.tmin,
          minTemperaturePosition: record.tminIdx,
          imax: record.imax,
          imaxIdx: record.imaxIdx,
          imin: record.imin,
          iminIdx: record.iminIdx,
          ...tempData,
          ...volData,
        };
      });

      const tempColumns =
        records.length > 0
          ? Object.keys(records[0])
              .filter((key) => key.startsWith('UnitTemp'))
              .map((key, index) => ({
                title: isEnglish ? `Temp of unit ${index + 1}(℃)` : `单元${index + 1}温度(℃)`,
                dataIndex: key,
                hideInSearch: true,
                width: 200,
              }))
          : [];

      const volColumns =
        records.length > 0
          ? Object.keys(records[0])
              .filter((key) => key.startsWith('UnitVol'))
              .map((key, index) => ({
                title: isEnglish ? `Voltage of unit ${index + 1}(V)` : `单元${index + 1}电压(V)`,
                dataIndex: key,
                hideInSearch: true,
                width: 200,
              }))
          : [];

      setDynamicColumns([...tempColumns, ...volColumns]);
      setData(records);
      // @ts-ignore
      setTotal(response.data.total);
    } else {
      setData([]);
      setTotal(0);
    }
    setLoading(false);
  };

  useEffect(() => {
    fetchData(params);
  }, [deviceCode, params]);

  const handleTableChange = (pagination: { current: number; pageSize: number }) => {
    setParams((prevParams) => ({
      ...prevParams,
      current: pagination.current,
      pageSize: pagination.pageSize,
    }));
  };

  const handleSearch = (values: any) => {
    const startDate = dayjs(values.startDate);
    const endDate = dayjs(values.endDate);
    if (endDate.diff(startDate, 'day') > 31) {
      message.warning(intl.formatMessage({ id: 'data.sDays' }));
      return;
    }
    setParams((prevParams) => ({
      ...prevParams,
      startDate: values.startDate,
      endDate: values.endDate,
    }));
  };

  const handleReset = () => {
    setParams({
      current: 1,
      pageSize: 20,
      startDate: dayjs().startOf('day').format('YYYY-MM-DDTHH:mm:ss'),
      endDate: dayjs().format('YYYY-MM-DDTHH:mm:ss'),
    });
    fetchData(params);
  };

  const scroll = {
    x: 'max-content',
    y: 'calc(100vh - 300px)',
  };

  const columnToAttrMap: Record<string, string> = {
    collectTime: 'ts', // 采集时间
    reportTime: 'reportTime', // 上报时间
    moduleName: 'bmuName', // 模组名称

    // 电流相关
    current: 'current', // 电流
    balanceCurrent: 'bcurrent', // 均衡电流

    // 电压相关
    moduleTotalVoltage: 'voltage', // 模组总电压
    cellAverageVoltage: 'cellAvgVol', // 单体平均电压
    maxVoltage: 'vmax', // 最大电压
    maxVoltagePosition: 'vmaxIdx', // 最大电压位置
    minVoltage: 'vmin', // 最小电压
    minVoltagePosition: 'vminIdx', // 最小电压位置

    // 温度相关
    cellAverageTemperature: 'cellAvgTemp', // 单体平均温度
    maxTemperature: 'tmax', // 最大温度
    maxTemperaturePosition: 'tmaxIdx', // 最大温度位置
    minTemperature: 'tmin', // 最小温度
    minTemperaturePosition: 'tminIdx', // 最小温度位置

    // 电流相关
    imax: 'imax', // 最大电流
    imaxIdx: 'imaxIdx', // 最大电流位置
    imin: 'imin', // 最小电流
    iminIdx: 'iminIdx', // 最小电流位置

    // 动态温度数据
    ...Array.from({ length: 20 }, (_, i) => ({
      [`UnitTemp${i + 1}`]: `temp${i + 1}`, // 单元温度 1-20
    })).reduce((acc, curr) => ({ ...acc, ...curr }), {}),

    // 动态电压数据
    ...Array.from({ length: 20 }, (_, i) => ({
      [`UnitVol${i + 1}`]: `vol${i + 1}`, // 单元电压 1-20
    })).reduce((acc, curr) => ({ ...acc, ...curr }), {}),
  };

  const exportDataReportFun = async (params: any) => {
    const startDate = dayjs(params.startDate);
    const endDate = dayjs(params.endDate);
    if (endDate.diff(startDate, 'day') > 3) {
      message.warning(intl.formatMessage({ id: 'data.selectTimeRange' }));
      return;
    }

    const attrNames =
      selectedColumns.length > 0
        ? selectedColumns
            .filter((col) => col !== 'index' && col !== 'pageIndex')
            .map((col) => columnToAttrMap[col] || col)
        : Object.values(columnToAttrMap);

    const exportParams: API.HistoryDataQuery = {
      areaId: Number(areaId),
      deviceType,
      deviceCode,
      startDate: dayjs(params.startDate).format('YYYY-MM-DD HH:mm:ss'),
      endDate: dayjs(params.endDate).format('YYYY-MM-DD HH:mm:ss'),
      attrNames,
    };

    await downloadFetch(exportDataReport, exportParams);
  };

  return (
    <div>
      <ProTable
        headerTitle={intl.formatMessage({ id: 'data.moduleNameDetail' })}
        search={{
          labelWidth: 80,
        }}
        columns={[...baseColumns, ...dynamicColumns]}
        scroll={scroll}
        columnsState={{
          value: Object.fromEntries(
            [...baseColumns, ...dynamicColumns]
              .filter((col) => col.dataIndex)
              .map((col) => [
                col.dataIndex,
                {
                  show:
                    selectedColumns.length === 0
                      ? true
                      : selectedColumns.includes(col.dataIndex as string),
                },
              ]),
          ),
          onChange: (stateMap) => {
            const newSelectedColumns = Object.entries(stateMap)
              // eslint-disable-next-line @typescript-eslint/no-unused-vars
              .filter(([_, value]) => value.show)
              .map(([key]) => key);
            setSelectedColumns(newSelectedColumns);
          },
          persistenceKey: 'battery-module-info-columns',
          persistenceType: 'localStorage',
        }}
        pagination={{
          current: params.current,
          pageSize: params.pageSize,
          total,
          onChange: (page, pageSize) => handleTableChange({ current: page, pageSize }),
        }}
        dataSource={data}
        loading={loading}
        onSubmit={handleSearch}
        onReset={handleReset}
        toolbar={{
          className: 'historyToobalr',
          actions: [
            <>
              <HandleBtn
                key="export"
                handleType="export"
                onClick={() => exportDataReportFun(params)}
              >
                {intl.formatMessage({ id: 'statistics.common.export' })}
              </HandleBtn>
              <Link key="monitor" to={`/stationmonitor/realtime?key=${selectedKeys}`}>
                {intl.formatMessage({ id: 'data.realtimeMonitor' })}
              </Link>
            </>,
          ],
        }}
      />
    </div>
  );
};

export default BatteryModuleInfo;
